﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.IO;
using System.Web;
using System.Drawing;

namespace HQWeb.SysManage.MaterialManage
{
    public partial class MaterialEdit : BasePage
    {
        //private String folder;
        protected void Page_Load(object sender, EventArgs e)
        {
            VerdictIsLogin();
            if (!IsPostBack)
            {
                BindDropDownList();
                BindElementList();
                string sign = Request.QueryString["sign"].ToString();
                if (sign.Equals("1"))  //编辑
                {
                    Edit();
                }
                else
                {
                    ddl_enty.SelectedValue = Request["type_id"];
                }
            }
        }

        #region 初始化页面下拉框
        public void BindDropDownList()
        {
            BLL.SysManage.T_PUB_DICTIONARY bll = new BLL.SysManage.T_PUB_DICTIONARY();
            List<Model.SysManage.T_PUB_DICTIONARY> il = bll.GetListArray(" FLAG = 1 order by ORDER_ID");
            BindDropData(ddl_color, 86, il);
            BindDropData(ddl_unit, 87, il);
        }
        #endregion

        #region 绑定元素分类列表
        private void BindElementList()
        {
            BLL.SysManage.T_PUB_MATERIALTYPE EntyBll = new BLL.SysManage.T_PUB_MATERIALTYPE();
            IList il = EntyBll.GetModelList("  ISUSED=1");
            ddl_enty.ClearSelection();
            ddl_enty.DataSource = il;
            ddl_enty.DataTextField = "TYPE_NAME"; //dropdownlist的Text的字段 
            ddl_enty.DataValueField = "TYPE_ID";//dropdownlist的Value的字段 
            ddl_enty.DataBind();
            if (Session["MATERIAL_TYPE"] != null)
            {
                ddl_enty.SelectedValue = Session["MATERIAL_TYPE"].ToString();
            }
        }
        #endregion

        #region 绑定颜色列表
        //private void BindColorList()
        //{
        //    BLL.Progect.T_PUB_ATTRIBUTE ColorBll = new BLL.Progect.T_PUB_ATTRIBUTE();
        //    IList il = ColorBll.GetModelByType(4);
        //    ddl_color.ClearSelection();
        //    ddl_color.DataSource = il;
        //    ddl_color.DataTextField = "ATTRIBUTE_NAME"; //dropdownlist的Text的字段 
        //    ddl_color.DataValueField = "ATTRIBUTE_ID";//dropdownlist的Value的字段 
        //    ddl_color.DataBind();
        //    ListItem item = new ListItem("无颜色", "0");
        //    ddl_color.Items.Add(item);
        //}
        #endregion

        #region 通过属性类型获取属性并绑定到下拉框
        protected void BindDropData(DropDownList drop_name, int type, List<Model.SysManage.T_PUB_DICTIONARY> il)
        {

            IEnumerable<Model.SysManage.T_PUB_DICTIONARY> lo = il.Where(p => p.PARENT_ID == type);
            drop_name.ClearSelection();
            drop_name.DataSource = lo;
            drop_name.DataTextField = "NAME"; //dropdownlist的Text的字段 
            drop_name.DataValueField = "ID";//dropdownlist的Value的字段 
            drop_name.DataBind();
            ListItem item = new ListItem("", "");
            item.Selected = true;
            drop_name.Items.Add(item);
        }
        #endregion

        #region 绑定计量单位列表
        //private void BindUnitList()
        //{
        //    BLL.Progect.T_PUB_ATTRIBUTE ColorBll = new BLL.Progect.T_PUB_ATTRIBUTE();
        //    IList il = ColorBll.GetModelByType(16);
        //    ddl_unit.ClearSelection();
        //    ddl_unit.DataSource = il;
        //    ddl_unit.DataTextField = "ATTRIBUTE_NAME"; //dropdownlist的Text的字段 
        //    ddl_unit.DataValueField = "ATTRIBUTE_ID";//dropdownlist的Value的字段 
        //    ddl_unit.DataBind();
        //    ListItem item = new ListItem("无计量单位", "0");
        //    ddl_unit.Items.Add(item);
        //}
        #endregion

        #region 编辑

        protected void Edit()
        {
            string strID = Request.QueryString["type_id"].ToString();
            BLL.SysManage.T_PUB_MATERIAL bll = new BLL.SysManage.T_PUB_MATERIAL();
            int temp;
            int.TryParse(strID, out temp);
            Model.SysManage.T_PUB_MATERIAL model = bll.GetModel(temp);
            if (model != null)
            {

                txtName.Text = model.MATERIAL_NAME;
                txtprice.Text = model.PRICE;
                txtremark.Text = model.REMARK;
                txtspecifications.Text = model.SPECIFICATIONS;
                ddl_enty.SelectedValue = Convert.ToString(model.TYPE_ID);
                ddl_color.SelectedValue = Convert.ToString(model.COLOR);
                ddl_unit.SelectedValue = Convert.ToString(model.UNIT);
                imgHeadPhoto.Src = model.IMAGEURL;
                btnSubmit.CommandName = "edit";
                btnSubmit.Text = "修 改";
                btnSubmit.CommandArgument = strID;
                labTitle.Text = "修改元素信息";
            }

        }


        #endregion

        #region 按钮事件

        //提交按钮
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            #region 保存图片
            string strFileName = null;
            string SavePath = "";
            string strFileUrl = this.fuHeadPhoto.PostedFile.FileName.Trim(); //取得文件路径
            if (strFileUrl != "" && strFileUrl != null)
            {
                string strImgType = strFileUrl.Substring(strFileUrl.LastIndexOf(".")); //取得文件扩展名  
                if (strImgType.ToLower() != ".gif" && strImgType.ToLower() != ".jpg" && strImgType.ToLower() != ".bmp" && strImgType.ToLower() != ".png")
                {
                    throw new Exception("只能保存.gif、.jpg、.bmp或.png格式的图片!");
                }
                string strGIud = System.Guid.NewGuid().ToString();
                strFileName = strGIud + strImgType.ToLower();
                //图片缩略图   
                Byte[] oFileByte = new byte[this.fuHeadPhoto.PostedFile.ContentLength];
                System.IO.Stream oStream = this.fuHeadPhoto.PostedFile.InputStream;
                System.Drawing.Image oImage = System.Drawing.Image.FromStream(oStream);

                int oWidth = oImage.Width;   //原图宽度    
                int oHeight = oImage.Height;   //原图高度    
                int tWidth = 100;   //设置缩略图初始宽度    
                int tHeight = 100;   //设置缩略图初始高度    

                //按比例计算出缩略图的宽度和高度    
                if (oWidth > oHeight || oWidth == oHeight)
                {
                    tHeight = (int)Math.Floor(Convert.ToDouble(oHeight) * (Convert.ToDouble(tWidth) / Convert.ToDouble(oWidth)));
                }
                else
                {
                    tWidth = (int)Math.Floor(Convert.ToDouble(oWidth) * (Convert.ToDouble(tHeight) / Convert.ToDouble(oHeight)));
                }

                //生成缩略原图    
                Bitmap tImage = new Bitmap(tWidth, tHeight);
                Graphics g = Graphics.FromImage(tImage);
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;   //设置高质量插值法    
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;//设置高质量,低速度呈现平滑程度    
                g.Clear(Color.Transparent);   //清空画布并以透明背景色填充    
                g.DrawImage(oImage, new Rectangle(0, 0, tWidth, tHeight), new Rectangle(0, 0, oWidth, oHeight), GraphicsUnit.Pixel);
                SavePath = Server.MapPath("../../Images/Element/") + strFileName;   //保存缩略图的物理路径    
                try
                {
                    //以JPG格式保存图片    
                    tImage.Save(SavePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
                catch (Exception ex)
                {
                    Universal.JS.Alert("生成元素缩略图失败！");
                    strFileName = "";
                }
                finally
                {
                    //释放资源    
                    oImage.Dispose();
                    g.Dispose();
                    tImage.Dispose();
                }
            }

           
            #endregion

            string strCommand = btnSubmit.CommandName;
            BLL.SysManage.T_PUB_MATERIAL bll = new BLL.SysManage.T_PUB_MATERIAL();
            Model.SysManage.T_PUB_MATERIAL model = null;
            if (strCommand.Equals("edit"))
            {
                string strID = btnSubmit.CommandArgument.ToString();
                int temp;
                int.TryParse(strID, out temp);
                model = bll.GetModel(temp);
            }
            if (model == null)
            {
                model = new Model.SysManage.T_PUB_MATERIAL();
            }
            model.REMARK = txtremark.Text.Trim();
            model.PRICE = txtprice.Text.Trim();
            model.MATERIAL_NAME = txtName.Text.Trim();
            model.TYPE_ID = Convert.ToInt32(ddl_enty.SelectedValue.Trim());
            if (ddl_color.SelectedValue != "")
            {
                model.COLOR = Convert.ToInt32(ddl_color.SelectedValue.Trim());
            }
            if (ddl_unit.SelectedValue != "")
            {
                model.UNIT = Convert.ToInt32(ddl_unit.SelectedValue.Trim());
            }
            model.SPECIFICATIONS = txtspecifications.Text.Trim();
            model.FLAG = Convert.ToInt32(bll.GetMaterialTypeState(model.TYPE_ID).Tables[0].Rows[0]["FALG"].ToString());
            model.ISUSED = 1;
            model.IMAGEURL = "../../Images/Element/" + strFileName;
            Session["MATERIAL_TYPE"] = model.TYPE_ID.ToString();
            if (strCommand.Equals("add"))
            {
                if (!bll.Exists(model.MATERIAL_ID))
                {
                    bll.Add(model);
                    Universal.CommonMethod.SaveOpreation(Convert.ToInt32(Session["USER_ID"]), "添加" + model.MATERIAL_NAME + "--元素", DateTime.Now);
                    if (Request["from"] != null)
                    {

                        Universal.JS.RunJS("gouBack()");
                    }
                    else
                    {
                        string strUrl = string.Format("MaterialList.aspx?pid={0}", model.TYPE_ID);
                        Response.Redirect(strUrl);
                    }
                }
                else
                {
                    Universal.JS.Alert("一个元素只能添加一个元素分类！");
                }
            }
            else
            {
                bll.Update(model);
                Universal.CommonMethod.SaveOpreation(Convert.ToInt32(Session["USER_ID"]), "更新" + model.MATERIAL_NAME + "--元素信息", DateTime.Now);
                if (Request["from"] != null)
                {

                    Universal.JS.RunJS("gouBack()");
                }
                else
                {
                    string strUrl = string.Format("MaterialList.aspx?pid={0}", model.TYPE_ID);
                    Response.Redirect(strUrl);
                }
            }
          
           
        }
    }
        #endregion
}